<!-- 检测点管理 -->
<template>
  <div class="jq-table h-full flex-col">
    <SearchForm @handle-reset-form-datas="handleResetFormDatas" :searchForm="searchForm" @handle-search="handleSearch"
      @chanFormValue="chanFormValue" />
    <div class="page-card h-full" v-loading="loading">
      <JqTable :tableColumn="tableColumn" :tableButtons="tableButtons" :itemsButtons="itemsButtons" :data="tableData"
        :page="page" @handle-selection-change="handleSelectionChange" @handle-size-change="handleSizeChange"
        @handle-current-change="handleCurrentChange">
        <!-- <slot name="checkPointAddress">
          
        </slot>-->
        
        <template #reserveTime>
          <el-table-column show-overflow-tooltip width="170" prop="reserveTime" label="预约时间" fit="true"
            show-header="true" align="left">
            <template #default="scope">
              <span>{{  scope.row['reserveTime'].slice(0,-3) }}</span>
            </template>
          </el-table-column>
        </template>
        <template #checkPointAddress>
          <el-table-column show-overflow-tooltip width="170" prop="checkPointAddress" label="检测点位置" fit="true"
            show-header="true" align="left">
            <template #default="scope">
              <span>{{ scope.row.checkType === 1 ? scope.row['address'] : '' }}</span>
            </template>
          </el-table-column>
        </template>
        <template #address>
          <el-table-column show-overflow-tooltip width="120" prop="address" label="上门地址" fit="true"
            show-header="true" align="left">
            <template #default="scope">
              <span>{{ scope.row.checkType === 2 ? scope.row['address'] : '' }}</span>
            </template>
          </el-table-column>
        </template>
      </JqTable>
      <AddOrUpdate v-if="showDialog" v-model:dialogVisible="showDialog" ref="addOrUpdateRef" :dialogDatas="dialogDatas"
        @update-list="updateList" />
      <CheckDialog v-if="showDialogCheck" v-model:dialogVisible="showDialogCheck" ref="checkRef"
        :dialogDatas="dialogDatas" @update-list="updateList" />
    </div>

    <!-- 取消预约 -->
    <el-dialog v-model="centerDialogVisible" title="请勾选取消预约原因" width="500" center>
      <el-form :model="cancelResonForm" label-width="auto">
        <el-radio-group v-model="cancelResonForm.reason"
          style="display: flex; flex-direction: column;align-items: flex-start;">
          <el-radio :label="'当日预约人数已满'">当日预约人数已满</el-radio>
          <el-radio :label="'预约时间调整,重新预约'"></el-radio>
          <el-radio :label="'无法接待'"></el-radio>
          <el-radio :label="'其他'"></el-radio>
        </el-radio-group>
        <!-- <el-radio-group v-model="cancelResonForm.reason">
          <el-radio :value="1">当日预约人数已满</el-radio>
          <el-radio :value="2">预约时间调整,重新预约</el-radio> 
          <el-radio :value="3">无法接待</el-radio>
          <el-radio :value="4">其他</el-radio>
        </el-radio-group> -->
        <el-input style="margin-top: 24px;height: 100px;" v-model="cancelResonForm.remark" placeholder="最多输入50字"
          maxlength="50" type="textarea"></el-input>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onCancelResonSubmit"> 确认 </el-button>
          <el-button @click="centerDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'Appointment' }); //检测点管理
import { reactive, ref, onMounted, computed } from 'vue';
import { useTable } from '@/hooks/useTable';
import { JqTable } from '@/components/Table/index';
import { useRouteStore } from '@/store';

import { AddOrUpdate } from './components';
import { CheckDialog } from './components'

import {
  getCheckPointsRequest
} from '@/api/checkPoint';

import { cancelReserve, getPageRequest } from "@/api/appointment";
import { orgOptionsRequest } from '@/api/common';
interface Row {
  reserveId: number;
  status: number;
  checkPointsId: number;
  statusConfig: object
}
const showDialog = ref(false)
const showDialogCheck = ref(false)

const routeStore = useRouteStore();
const centerDialogVisible = ref(false);
const cancelResonForm = reactive({
  reserveId: '',
  reason: '当日预约人数已满',
  remark: ''
})
const onCancelResonSubmit = () => {
  cancelReserve(cancelResonForm).then((res: any) => {
    centerDialogVisible.value = false
    getList();
  })
}
let orgIdDatas = reactive([]); //归属组织下拉数据
let checkIdDatas = reactive([]); // 监测点
let searchFormParams = reactive({
  // deviceQueryReq: {}
}); //查询参数


const addOrUpdateRef = ref();

let searchForm = reactive([
  {
    type: 'input',
    value: '',
    label: '用户查询',
    placeholder: '用户姓名/手机',
    eName: 'name'
  },
  {
    type: 'select',
    value: '',
    label: '预约机构',
    placeholder: '全部',
    options: () => {
      return orgIdDatas;
    },
    eName: 'orgId'
  },
  {
    type: 'select',
    value: '',
    label: '预约检测点',
    placeholder: '全部',
    options: () => {
      return checkIdDatas;
    },
    eName: 'checkId'
  },
  {
    type: 'select',
    value: '',
    label: '预约方式',
    placeholder: '全部',
    options: () => {
      return [{ id: 1, name: '到检测点' }, { id: 2, name: '顾问上门' }];//待激活去掉
    },
    eName: 'checkType'
  },
  {
    type: 'select',
    value: '',
    label: '状态',
    placeholder: '全部',
    options: () => {
      return [{ id: 0, name: '预约待确认' }, { id: 1, name: '预约成功' }, { id: 2, name: '预约取消' },];//待激活去掉
    },
    eName: 'status'
  },
  {
    type: 'date',
    value: '',
    label: '预约时间',
    eName: 'times'
  }
]);
const tableColumn = reactive([
  //内置
  { label: '预约时间', prop: 'reserveTime', minWidth: '180', slot: true  },
  { label: '用户姓名', prop: 'name', minWidth: '120' },
  { label: '手机号', prop: 'mobile', minWidth: '120' },
  { label: '状态', prop: 'statusName', minWidth: '110' },
  { label: '预约机构', prop: 'orgName', minWidth: '120' },
  { label: '预约检测点', prop: 'checkPointName', minWidth: '120' },
  { label: '检测方式', prop: 'checkTypeName', minWidth: '90' },
  { label: '检测点地址', prop: 'checkPointAddress', minWidth: '170', slot: true },
  { label: '上门顾问', prop: 'healthName', minWidth: '100' },
  { label: '上门地址', prop: 'address', minWidth: '120', slot: true },
  { label: '创建时间', prop: 'createTime', minWidth: '180' },
]);
let tableButtons = reactive([
  //来源于数据
  {
    id: 64,
    type: 'primary',
    label: '添加',
    perms: 'reserve:btn:save',
    onClick: async () => {
      showDialog.value = true
      dialogDatas = {
        title: '新增',
        type: 'add',
      };
    }
  },
]);
let itemsButtons = reactive([
  //来源于数据
  {
    id: 69,
    type: 'success',
    label: '查看',
    perms: 'reserve:btn:view',
    showTypeList: [0, 1, 2],
    onClick: (row: Row) => {
      // router.push('/myTest');
      showDialogCheck.value = true
      dialogDatas = {
        title: '查看',
        type: 'check',
        datas: row,
      };
    }
  },
  //来源于数据
  {
    id: 65,
    type: 'success',
    label: '编辑',
    perms: 'reserve:btn:edit',
    showTypeList: [0],
    onClick: (row: Row) => {
      // router.push('/myTest');
      showDialog.value = true
      dialogDatas = {
        title: '编辑',
        type: 'edit',
        datas: row,
      };
    }
  },
  {
    id: 66,
    type: 'primary',
    perms: 'reserve:btn:cancel',
    label: '取消预约',
    showTypeList: [0, 1],
    onClick: (row: Row) => {
      centerDialogVisible.value = true
      cancelResonForm.reserveId = row.reserveId
      cancelResonForm.reason = '当日预约人数已满'
      cancelResonForm.remark = ''
    }
  }
]);

const currentMenudatas = computed(() => routeStore.currentMenudatas);
const oldOrgId = ref('')
const chanFormValue = (formParamsDatats: {}) => {
  if (formParamsDatats.orgId && formParamsDatats.orgId !== oldOrgId.value) {
    formParamsDatats.checkId = ''
    oldOrgId.value = formParamsDatats.orgId
    searchForm = searchForm.map((item) => {
      if (item.value) {
        if (item.eName === 'checkId') {
          item.value = '';
        }
      }
      return item;
    });
    // 根据机构获取检测点数据
    getCheckPointsRequest({
      pageSize: 999,
      pageNum: 1,
      orgId: formParamsDatats.orgId
    }).then(res => {
      checkIdDatas = res.data.list.map(item => {
        return {
          id: item.id,
          name: item.pointName
        }
      })
    })
  }
  searchFormParams = formParamsDatats
  searchFormParams.beginDate = searchFormParams.startCreateTime?.split(' ')[0] || ''
  searchFormParams.endDate = searchFormParams.endCreateTime?.split(' ')[0] || ''
  delete searchFormParams.startCreateTime
  delete searchFormParams.endCreateTime
  console.log(searchFormParams);


}

let dialogDatas = reactive({});
const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange } =
  useTable({
    apiFn: getPageRequest,
    params: () => searchFormParams
  });
/* 表格多选事件 */
const handleSelectionChange = (val: []) => {
  multipleSelection = val;
};
/* 表单查询 */
const handleSearch = (searchFormParamsDatats: {}) => {
  Object.assign(searchFormParams, searchFormParamsDatats);
  getList();
};

/* 高级搜索重置 */
const handleResetFormDatas = () => {
  searchFormParams = {}
  searchForm = searchForm.map((item) => {
    if (item.value || item.value === 0) {
      if (item.type === 'cascader') {
        item.value = [];
      } else {
        item.value = '';
      }
    }
    return item;
  });
  getList();

};
const updateList = () => {
  getList();
  showDialogCheck.value = false
  showDialog.value = false
}


/* 获取归属检测点数据 */
// const getCheckPointsOptionsDatas = async () => {
//   const data: any = await getCheckPointsOptionsRequest({});
//   checkPointsOptionsDatas = data.data;
// };
/* 归属组织 */
const getOrgOptionsDatas = async () => {
  const data: any = await orgOptionsRequest({ containBase: false });
  orgIdDatas = data.data;
};
/* 获取监测点 */
// const getOrgOptionsDatas = async () => {
//   const data: any = await orgOptionsRequest({ containBase: false });
//   orgIdDatas = data.data;
// };
//根据数据返回按钮信息控制权限
/* params
{
  datas:本地配置的按钮数据（tableButtons/itemsButtons)
}
*/
const tableButtonsPermission = (datas: any[], datas1: any[]) => {
  return datas.filter(function (item1: { perms: string }) {
    return datas1.find(function (item2: { perms: string }) {
      return item1.perms === item2.perms;
    });
  });
};


onMounted(() => {
  getOrgOptionsDatas();
  if (!currentMenudatas.value) {
    return
  }
  tableButtons = tableButtonsPermission(tableButtons, currentMenudatas.value.tableButtons); //tableButtons根据数据返回按钮信息控制权限
  itemsButtons = tableButtonsPermission(itemsButtons, currentMenudatas.value.itemsButtons); //itemButtons根据数据返回按钮信息控制权限
});
</script>
<style scoped>
.packageCardcontainer {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;

  >.card {
    flex: 0 0 18%;
    min-width: 18%;
    margin-right: calc(9.99% / 4);
    margin-bottom: 10px;

    /* // 每行最后一个卡片 */
    &:nth-child(5n) {
      margin-right: 0;
    }

    /* // 最后一个卡片 */
    &:last-child {
      margin-right: auto;
    }
  }
}
</style>
